package com.geniusk.wss.utils;

import com.geniusk.wss.UserChannelSession;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.geniusk.wss.ChatHandler.wssChannelGroup;

@Component
@Slf4j
public class WsUtil {

    public static void sendToWs(Long identityId, String message){
        // 从全局用户Channel关系中获取接受方的channel
        List<Channel> receiverChannelList = UserChannelSession.getChannelListByUserId(identityId);
        if (receiverChannelList == null) {
            // 接受者离线，推送消息
            log.info("接收用户离线, 接受者身份ID:{}",identityId);
        } else {
            // 当receiverChannel不为空的时候，从ChannelGroup去查找对应的channel是否存在
            for(Channel receiverChannel: receiverChannelList){
                Channel findChannel = wssChannelGroup.find(receiverChannel.id());
                if (findChannel != null) {
                    // 用户在线
                    receiverChannel.writeAndFlush(new TextWebSocketFrame(message));
                }
            }
        }
    }
}
